package com.bear.atlassianmcp.jira.mcp.tools;

import com.bear.atlassianmcp.jira.model.JiraAttachment;
import com.bear.atlassianmcp.jira.service.JiraService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 附件管理MCP工具
 * 提供Issue附件的查看、上传、删除等功能
 */
@Service
public class AttachmentTools {

    private static final Logger logger = LoggerFactory.getLogger(AttachmentTools.class);

    private final JiraService jiraService;

    @Autowired
    public AttachmentTools(JiraService jiraService) {
        this.jiraService = jiraService;
    }

    /**
     * 获取Issue的所有附件信息
     *
     * @param issueKey Issue键值，如"PROJ-123"
     * @param context 工具上下文
     * @return Issue附件列表的格式化文本
     */
    @Tool(description = "获取Jira Issue的所有附件信息，包括文件名、大小、上传者、上传时间等详细信息")
    public String getIssueAttachments(@ToolParam(description = "Issue键值，格式如PROJ-123") String issueKey, ToolContext context) {
        logger.info("MCP Tool: Getting attachments for issue {}", issueKey);

        try {
            List<JiraAttachment> attachments = jiraService.getIssueAttachments(issueKey, context);
            
            if (attachments.isEmpty()) {
                return String.format("📎 Issue %s 没有附件。", issueKey);
            }
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("📎 Issue %s 的附件列表 (%d个)：\n\n", issueKey, attachments.size()));
            
            for (int i = 0; i < attachments.size(); i++) {
                JiraAttachment attachment = attachments.get(i);
                result.append(String.format("%d. %s\n", i + 1, attachment.toSimpleString()));
                result.append(String.format("   ID: %s\n", attachment.getId()));
                result.append(String.format("   类型: %s\n", attachment.getMimeType()));
                result.append(String.format("   上传时间: %s\n", attachment.getCreated()));
                
                if (attachment.hasThumbnail()) {
                    result.append("   🖼️ 有缩略图\n");
                }
                result.append("\n");
            }
            
            logger.info("Successfully retrieved {} attachments for issue {} via MCP", attachments.size(), issueKey);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get attachments for issue {} via MCP: {}", issueKey, e.getMessage());
            return "❌ 获取附件列表失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取单个附件的详细信息
     *
     * @param attachmentId 附件ID
     * @param context 工具上下文
     * @return 附件详细信息的格式化文本
     */
    @Tool(description = "获取Jira Issue指定附件的详细信息，包括下载链接、文件属性等完整信息")
    public String getAttachmentDetails(@ToolParam(description = "附件ID，可通过getIssueAttachments工具获取") String attachmentId, ToolContext context) {
        logger.info("MCP Tool: Getting attachment details for {}", attachmentId);

        try {
            JiraAttachment attachment = jiraService.getAttachment(attachmentId, context);
            
            String result = String.format(
                "📎 附件详细信息：\n\n%s\n" +
                "💡 提示：可以通过下载链接直接访问文件。",
                attachment.toFormattedString()
            );
            
            logger.info("Successfully retrieved attachment details for {} via MCP", attachmentId);
            return result;
            
        } catch (Exception e) {
            logger.error("Failed to get attachment details for {} via MCP: {}", attachmentId, e.getMessage());
            return "❌ 获取附件详情失败。原因：" + e.getMessage();
        }
    }

    /**
     * 上传附件到Issue
     *
     * @param issueKey Issue键值
     * @param filePath 文件路径（绝对路径或相对路径），当提供markdownContent时可为空
     * @param markdownContent Markdown格式的文本内容，将创建为.md文件上传
     * @param filename 当提供markdownContent时的文件名（不含扩展名），默认使用时间戳
     * @param context 工具上下文
     * @return 上传结果信息
     */
    @Tool(description = "上传文件或Markdown文本作为附件到指定的Jira Issue。支持两种模式：1)上传现有文件 2)将Markdown文本创建为.md文件上传")
    public String uploadIssueAttachment(@ToolParam(description = "Issue键值，格式如PROJ-123") String issueKey,
                                       @ToolParam(required = false, description = "文件路径（绝对路径或相对路径），当提供markdownContent时可为空") String filePath,
                                       @ToolParam(required = false, description = "Markdown格式的文本内容，将创建为.md文件上传到Issue") String markdownContent,
                                       @ToolParam(required = false, description = "当提供markdownContent时的文件名（不含.md扩展名），默认使用时间戳") String filename,
                                       ToolContext context) {
        logger.info("MCP Tool: Uploading attachment to issue {} from file {} or markdown content", issueKey, filePath);

        try {
            // 参数验证
            if ((filePath == null || filePath.trim().isEmpty()) &&
                (markdownContent == null || markdownContent.trim().isEmpty())) {
                return "❌ 必须提供文件路径或Markdown内容中的一个。\n" +
                       "💡 使用方式：\n" +
                       "  1. 上传现有文件：提供filePath参数\n" +
                       "  2. 上传Markdown文本：提供markdownContent参数";
            }

            if (filePath != null && !filePath.trim().isEmpty() &&
                markdownContent != null && !markdownContent.trim().isEmpty()) {
                return "❌ 不能同时提供文件路径和Markdown内容，请选择其中一种方式。";
            }

            File fileToUpload;
            boolean isTemporaryFile = false;
            String actualFilePath;

            // 处理Markdown内容上传
            if (markdownContent != null && !markdownContent.trim().isEmpty()) {
                // 验证Markdown内容
                if (markdownContent.length() > 1024 * 1024) { // 1MB限制
                    return "❌ Markdown内容过大，请限制在1MB以内。";
                }

                // 生成文件名
                String mdFilename;
                if (filename != null && !filename.trim().isEmpty()) {
                    mdFilename = filename.trim() + ".md";
                } else {
                    String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
                    mdFilename = "markdown_" + timestamp + ".md";
                }

                // 创建临时文件
                try {
                    Path tempFile = Files.createTempFile("jira_attachment_", "_" + mdFilename);
                    Files.write(tempFile, markdownContent.getBytes("UTF-8"), StandardOpenOption.WRITE);

                    fileToUpload = tempFile.toFile();
                    actualFilePath = tempFile.toString();
                    isTemporaryFile = true;

                    logger.info("Created temporary markdown file: {}", actualFilePath);

                } catch (IOException e) {
                    logger.error("Failed to create temporary markdown file: {}", e.getMessage());
                    return "❌ 创建临时Markdown文件失败：" + e.getMessage();
                }

            } else {
                // 处理文件路径上传
                actualFilePath = filePath;
                fileToUpload = new File(filePath);

                // 验证文件是否存在
                if (!fileToUpload.exists()) {
                    return "❌ 文件不存在：" + filePath +
                           "\n💡 请检查文件路径是否正确，支持绝对路径和相对路径。";
                }

                if (!fileToUpload.isFile()) {
                    return "❌ 指定路径不是文件：" + filePath;
                }

                if (!fileToUpload.canRead()) {
                    return "❌ 无法读取文件：" + filePath +
                           "\n💡 请检查文件权限。";
                }
            }

            // 检查文件大小（可选的限制检查）
            long fileSizeInMB = fileToUpload.length() / (1024 * 1024);
            if (fileSizeInMB > 100) { // 假设限制为100MB
                if (isTemporaryFile) {
                    fileToUpload.delete(); // 清理临时文件
                }
                return String.format("❌ 文件过大：%.1f MB\n💡 建议上传小于100MB的文件。",
                                   (double) fileToUpload.length() / (1024 * 1024));
            }

            String result = jiraService.uploadAttachment(issueKey, actualFilePath, context);

            String uploadType = isTemporaryFile ? "Markdown文本" : "文件";
            String sourceInfo = isTemporaryFile ?
                String.format("内容长度: %d 字符", markdownContent.length()) :
                String.format("文件路径: %s", filePath);

            String response = String.format(
                "✅ 成功上传%s到Issue %s！\n" +
                "文件名: %s\n" +
                "文件大小: %.1f KB\n" +
                "%s\n" +
                "上传时间: %s\n" +
                "💡 附件已添加到Issue，可以在Issue页面查看。",
                uploadType,
                issueKey,
                fileToUpload.getName(),
                (double) fileToUpload.length() / 1024,
                sourceInfo,
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            );

            // 清理临时文件
            if (isTemporaryFile) {
                try {
                    fileToUpload.delete();
                    logger.info("Cleaned up temporary file: {}", actualFilePath);
                } catch (Exception cleanupException) {
                    logger.warn("Failed to cleanup temporary file {}: {}", actualFilePath, cleanupException.getMessage());
                }
            }

            logger.info("Successfully uploaded {} attachment to issue {} via MCP", uploadType, issueKey);
            return response;

        } catch (Exception e) {
            logger.error("Failed to upload attachment to issue {} via MCP: {}", issueKey, e.getMessage());

            // 在异常情况下也要清理临时文件
            if (markdownContent != null && !markdownContent.trim().isEmpty()) {
                try {
                    // 尝试清理可能创建的临时文件
                    Path tempDir = Files.createTempDirectory("cleanup").getParent();
                    Files.list(tempDir)
                        .filter(path -> path.getFileName().toString().startsWith("jira_attachment_"))
                        .forEach(path -> {
                            try {
                                Files.deleteIfExists(path);
                            } catch (IOException ignored) {}
                        });
                } catch (Exception ignored) {}
            }

            return "❌ 上传附件失败。原因：" + e.getMessage() +
                   "\n💡 请检查文件路径、Issue权限、网络连接或Markdown内容格式。";
        }
    }

    /**
     * 删除Issue附件
     *
     * @param attachmentId 附件ID
     * @param context 工具上下文
     * @return 删除结果信息
     */
    // @Tool(description = "删除指定的Jira Issue附件，需要相应的删除权限")
    public String deleteIssueAttachment(String attachmentId, ToolContext context) {
        logger.info("MCP Tool: Deleting attachment {}", attachmentId);

        try {
            // 先获取附件信息用于确认
            JiraAttachment attachment = jiraService.getAttachment(attachmentId, context);
            String filename = attachment.getFilename();

            String result = jiraService.deleteAttachment(attachmentId, context);
            
            String response = String.format(
                "✅ 成功删除附件！\n" +
                "附件ID: %s\n" +
                "文件名: %s\n" +
                "删除时间: %s\n" +
                "⚠️ 注意：删除操作不可撤销。",
                attachmentId,
                filename,
                java.time.LocalDateTime.now().toString()
            );
            
            logger.info("Successfully deleted attachment {} via MCP", attachmentId);
            return response;
            
        } catch (Exception e) {
            logger.error("Failed to delete attachment {} via MCP: {}", attachmentId, e.getMessage());
            return "❌ 删除附件失败。原因：" + e.getMessage() + 
                   "\n💡 请检查附件ID是否正确以及是否有删除权限。";
        }
    }

    /**
     * 获取Issue附件的简要统计信息
     * 
     * @param issueKey Issue键值
     * @return 附件统计信息
     */
    @Tool(description = "获取Issue附件的统计信息，包括附件数量、总大小、文件类型分布等")
    public String getIssueAttachmentSummary(String issueKey, ToolContext context) {
        logger.info("MCP Tool: Getting attachment summary for issue {}", issueKey);
        
        try {
            List<JiraAttachment> attachments = jiraService.getIssueAttachments(issueKey, context);
            
            if (attachments.isEmpty()) {
                return String.format("📊 Issue %s 附件统计：\n📎 附件数量: 0", issueKey);
            }
            
            // 统计信息
            long totalSize = 0;
            int imageCount = 0;
            int documentCount = 0;
            int otherCount = 0;
            
            for (JiraAttachment attachment : attachments) {
                if (attachment.getSize() != null) {
                    totalSize += attachment.getSize();
                }
                
                String mimeType = attachment.getMimeType();
                if (mimeType != null) {
                    if (mimeType.startsWith("image/")) {
                        imageCount++;
                    } else if (mimeType.contains("document") || mimeType.contains("pdf") || 
                              mimeType.contains("text") || mimeType.contains("word") || 
                              mimeType.contains("excel") || mimeType.contains("powerpoint")) {
                        documentCount++;
                    } else {
                        otherCount++;
                    }
                } else {
                    otherCount++;
                }
            }
            
            String totalSizeFormatted;
            if (totalSize < 1024) {
                totalSizeFormatted = totalSize + " B";
            } else if (totalSize < 1024 * 1024) {
                totalSizeFormatted = String.format("%.1f KB", totalSize / 1024.0);
            } else {
                totalSizeFormatted = String.format("%.1f MB", totalSize / (1024.0 * 1024.0));
            }
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("📊 Issue %s 附件统计：\n\n", issueKey));
            result.append(String.format("📎 附件总数: %d\n", attachments.size()));
            result.append(String.format("💾 总大小: %s\n", totalSizeFormatted));
            result.append(String.format("🖼️ 图片文件: %d\n", imageCount));
            result.append(String.format("📄 文档文件: %d\n", documentCount));
            result.append(String.format("📦 其他文件: %d\n", otherCount));
            
            logger.info("Successfully generated attachment summary for issue {} via MCP", issueKey);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get attachment summary for issue {} via MCP: {}", issueKey, e.getMessage());
            return "❌ 获取附件统计失败。原因：" + e.getMessage();
        }
    }
}
